package cn.wsalix.msg.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.anlaser.service.impl.CommonServiceImpl;
import cn.anlaser.utils.SearchFilter;
import cn.anlaser.utils.SearchFilter.Operator;
import cn.wsalix.admin.entity.SysUser;
import cn.wsalix.admin.service.UserService;
import cn.wsalix.msg.entity.Issue;
import cn.wsalix.msg.repository.IssueRepository;
import cn.wsalix.msg.service.IssueService;
import cn.wsalix.user.form.IssueForm;

@Service("issueService")
public class IssueServiceImpl extends
		CommonServiceImpl<IssueForm, IssueRepository, Issue> implements
		IssueService {
	@Autowired
	private IssueRepository issueRepository;
	@Autowired
	private UserService userService;
	@Override
	public String module() {
		return "/user/issue";
	}

	@Override
	public IssueRepository getRepository() {
		return issueRepository;
	}

	@Override
	public Class<Issue> getEntityClazz() {
		return Issue.class;
	}

	@Override
	public Map<String, SearchFilter> buildByForm(IssueForm form) {
		Map<String, Object> searchParams = new HashMap<String, Object>();
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		if (form.getId() != null && form.getId() != 0) {
			filters.put("id", new SearchFilter("id", Operator.EQ, form.getId()));
		}
		if (form.getFkId() != null && form.getFkId() != 0) {
			filters.put("fkId", new SearchFilter("fkId", Operator.EQ, form.getFkId()));
		}
		if (form.getPresbyterId() != null && form.getPresbyterId() != 0) {
			filters.put("presbyterId", new SearchFilter("presbyterId", Operator.EQ, form.getPresbyterId()));
		}
		return filters;
	}
	@Transactional
	@Override
	public Issue findByProductId(Long productId,Long userId) {
		IssueForm issueForm = new IssueForm();
		List<Issue> resLst = findByForm(issueForm);
		if (resLst.size() != 1) {
			if (resLst.size() > 1) {
				return resLst.get(0);
			}
			SysUser user=userService.findById(userId);
			//没有商品主题时,生成商品主题
			Issue issue=new Issue();
			issue.setFkId(productId);
			issue.setPresbyterId(userId);
			issue.setPresbyter(user.getUsername());
			issue.setWaiterId(9999l);
			issue.setWaiterName("客服");
			issue=super.add(issue);
			return issue;
		} else {
			return resLst.get(0);
		}
	}

}
